package com.th.therp.controller;

import com.th.therp.exception.BaseException;
import com.th.therp.pojo.emtity.Vendor;
import com.th.therp.pojo.result.Result;
import com.th.therp.service.VendorService;
import jakarta.validation.Valid;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 供应商请求控制器
 */
@Log4j2
@RestController
@RequestMapping("vendor")
public class VendorController {

    @Autowired
    private VendorService vendorService;

    //查询全部供应商
    @GetMapping("/page")
    @ResponseBody
    public Result<List<Vendor>> list(){
        log.info("查询全部供应商");
        List<Vendor> vendorList = vendorService.list();
        return Result.success(vendorList);
    }

    //新增供应商
    @PostMapping()
    @ResponseBody
    public Result add(@Valid @RequestBody Vendor vendor, BindingResult bindingResult){
        log.info("新增供应商:{}",vendor);
        if(bindingResult.hasErrors()){throw new BaseException("格式不正确");}
        vendorService.add(vendor);
        return Result.success();
    }

    //修改供应商
    @PutMapping()
    @ResponseBody
    public Result update(@Valid @RequestBody Vendor vendor, BindingResult bindingResult ){
        log.info("修改供应商:{}",vendor);
        if(bindingResult.hasErrors()){throw new BaseException("格式不正确");}
        vendorService.update(vendor);
        return Result.success();
    }

    //删除供应商
    @DeleteMapping()
    @ResponseBody
    public Result delete(@RequestParam List<Integer> ids){
        log.info("删除供应商:{}",ids);
        vendorService.delete(ids);
        return Result.success();
    }
}